#!/usr/bin/python
# coding=utf-8

import sys, datetime, json, logging

from xpy3lib.utils import db_utils as util

from sicost.config import app_config
from xpy3lib.XLogger import XLogger
from xpy3lib.utils.XUtils import XUtils
from xpy3lib.utils.XDateTimeUtils import XDateTimeUtils

from sicost.DeleteRDSJob import DeleteRDSJob

profile = 'dev'


def delete_rds(source_schema, source_table, account_period_end):
    status = 0
    try:
        info = XUtils.get_git_info()
    except Exception as e:
        info = {'message': 'no_git'}

    level = logging.ERROR if profile == 'prod' else logging.NOTSET
    XLogger.getInstance(p_level=level, p_name_key_word='sicost').logger.error(
        '\n%s' % json.dumps(info, sort_keys=True, indent=4))

    config = app_config[profile]

    try:

        db_conn_rds = util.getConnectionDb2(config.DB_HOST_RDS_DB2,
                                            config.DB_PORT_RDS_DB2,
                                            config.DB_DBNAME_RDS_DB2,
                                            config.DB_USER_RDS_DB2,
                                            config.DB_PASSWORD_RDS_DB2)
        XLogger.getInstance().logger.info('connect db_conn_rds success')
    except Exception as e:

        db_conn_rds = None
        XLogger.getInstance().logger.critical(str(e))
    try:
        run_delete_rds(p_config=config, p_db_conn_rds=db_conn_rds, p_source_schema=source_schema,
                       p_source_table=source_table, p_account_period_end=account_period_end)
    except Exception as e:
        XLogger.getInstance().logger.critical(str(e))
    # run_delete_rds(p_config=config, p_db_conn_rds=db_conn_rds, p_source_schema=source_schema,
    #                p_source_table=source_table, p_account_period_end=account_period_end)

    try:

        util.closeConnection(db_conn_rds)
    except Exception as e:
        XLogger.getInstance().logger.error(str(e))
        status = 1

    return status


def run_delete_rds(p_config=None, p_db_conn_rds=None, p_source_schema=None, p_source_table=None,
                   p_account_period_end=None):
    DeleteRDSJob(p_config=p_config,
                 p_db_conn_rds=p_db_conn_rds,
                 p_source_schema=p_source_schema,
                 p_source_table=p_source_table,
                 p_account_period_end=p_account_period_end).execute()


if __name__ == '__main__':
    now = datetime.datetime.now()

    # onemonth = datetime.timedelta(days=30)
    # prev_month = now - onemonth
    # s = datetime.datetime(year=prev_month.year, month=prev_month.month, day=prev_month.day, hour=20, minute=0,
    #                       second=0)
    # # e = datetime.datetime(year=now.year, month=now.month, day=now.day, hour=20, minute=0, second=0)
    # account_period_end = s.strftime('%Y%m%tmp_dict%H%M%S')

    p_month_1day = XDateTimeUtils.advance(now, p_months=-1)
    p_month_1 = datetime.datetime(year=p_month_1day.year, month=p_month_1day.month).strftime('%Y%m')
    s = datetime.datetime(year=p_month_1.year, month=p_month_1.month, day=p_month_1.day, hour=20, minute=0,
                          second=0)
    account_period_end = s.strftime('%Y%m%tmp_dict%H%M%S')
    # p_day_1 = (start - datetime.timedelta(days=1)).strftime("%Y%m%tmp_dict")
    # p_day_2 = (start - datetime.timedelta(days=2)).strftime("%Y%m%tmp_dict")
    delete_rds('BGTARAS1', 'T_ADS_FACT_SICB_MO0101', account_period_end)
    delete_rds('BGTARAS1', 'T_ADS_FACT_SICB_CA0001', account_period_end)
    delete_rds('BGTARAS1', 'T_ADS_FACT_SICB_CD0101', account_period_end)
    delete_rds('BGTARAS1', 'T_ADS_FACT_SICB_CD0102', account_period_end)
    delete_rds('BGTARAS1', 'T_ADS_FACT_SICB_CD0103', account_period_end)
    delete_rds('BGTARAS1', 'T_ADS_FACT_SICB_CD0104', account_period_end)
    delete_rds('BGTARAS1', 'T_ADS_FACT_SICB_CD0105', account_period_end)
    delete_rds('BGTARAS1', 'T_ADS_FACT_SICB_CD0106', account_period_end)
    delete_rds('BGTARAS1', 'T_ADS_FACT_SICB_CD0201', account_period_end)
    delete_rds('BGTARAS1', 'T_ADS_FACT_SICB_DP0102', account_period_end)
    delete_rds('BGTARAS1', 'T_ADS_FACT_SICB_DP0103', account_period_end)

    elapsed = float((datetime.datetime.now() - now).seconds)
    print("Time Used 4 All ----->>>> %f seconds" % (elapsed))
